// pages/financingapply/financingapply.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cityName: "",
    form: {
      contactName: "",
      contactPhone: "",
      enterpriseCode: "",
      enterpriseName: "",
      loanAmount: "",
      isoneloan: false,
      ispledge: false,
      pledgegood: ""
    },
    lianxiren: "11111",
    banklists: [],
    banklist: [],
    selectbanklist: [],
    proselectisshow: false,
    applysuccessdialog: false,
    searchbank: "",
    // 企业列表下拉框
    dropdownIsShow: false,
    prolist: [],
    prosearchlodding: false,
    proinputisfocus: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.test()
    // 获取意向贷款银行列表
    // this.getBanklist()
    // 获取当前城市
    this.getLocation()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 清除表单
  clearForm: function() {
    this.setData({
      ['form.enterpriseName']: "",
      ['form.enterpriseCode']: "",
      ['form.contactName']: "",
      ['form.contactPhone']: "",
      ['form.loanAmount']: "",
      ['form.isoneloan']: false,
      ['form.pledgegood']: "",
      ['form.ispledge']: false,
      cityName: getApp().globalData.cityName,
      banklist: [],
    })
    getApp().globalData.seleproinfo = {}
    getApp().globalData.banklist = []
  },
  getLocation: function() {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success(pos) {
        console.log(pos);
        getApp().globalData.request("/coordinate/getCityNameByCoordinate", {
          lng: pos.longitude,
          lat: pos.latitude
        }, "POST").then(res => {
          console.log(res);
          if (res.code == 1) {
            that.setData({
              cityName: res.data.cityName
            })
            let app = getApp();
            app.globalData.cityName = res.data.cityName
          } else {
            // Toast(res.message)
          }
        })
      }
    })
  },
  getBanklist: async function() {
    const {
      data
    } = await getApp().globalData.request("/financing/getOrderedBanks", {
      city: this.data.cityName
    }, "POST")
    console.log(data);
    this.setData({
      banklists: data.banks
    })
  },
  selectPro: async function() {
    wx.navigateTo({
      url: '/pages/prolist/prolist',
    })
  },

  // 企业名称获取焦点
  opendropdown: function() {
    if (this.data.form.enterpriseName.length > 0) {
      this.setData({
        dropdownIsShow: true
      })
    }
  },
  closedropdown: function() {
    this.setData({
      dropdownIsShow: false
    })
  },
  // 企业名称
  setproname: function(e) {
    console.log(e);
    this.setData({
      ['form.enterpriseName']: e.detail.value,
    })
    this.getProlist()
  },
  getProlist: function() {
    var _this = this
    // wx.showLoading({
    //   title: '搜索中',
    // })
    let prams = {
      corpName: this.data.form.enterpriseName,
      pageNum: 1,
      pageSize: 10,
      region: this.data.cityName
    }
    console.log(prams);
    this.setData({
      prosearchlodding: true
    })
    if (this.data.form.enterpriseName.length > 0) {
      getApp().globalData.request('/financing/selectPageCorpByName', prams, "POST", ).then(res => {
        console.log("++++++++", res);
        // wx.hideLoading()
        if (res.data.records.length > 0) {
          _this.setData({
            prolist: res.data.records,
            prosearchlodding: false
          })
          this.opendropdown()
        } else {
          _this.setData({
            prolist: [],
            prosearchlodding: false
          })
          this.closedropdown()
        }
      })
    } else {
      _this.setData({
        prolist: []
      })
      this.closedropdown()
    }


  },
  proitemClick: function(e) {
    console.log(e.currentTarget.dataset.proname);
    this.setData({
      ['form.enterpriseName']: e.currentTarget.dataset.proname,
      ['form.enterpriseCode']: e.currentTarget.dataset.prokey,
    })
    this.setData({
      dropdownIsShow: false,
      prolist: [],
      proinputisfocus: true
    })
  },
  // 代码
  setprocode: function(e) {
    console.log(e);
    this.setData({
      ['form.enterpriseCode']: e.detail.value
    })
  },
  procodeFocus: function() {
    this.closedropdown()
  },
  procodeBlur: function() {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    if (reg.test(this.data.form.enterpriseCode)) {
      Toast("企业证件代码格式不正确！");
    } else {
      // Toast("没有包含汉字！");
    }
  },
  // x选择地址
  selectPsi: function() {
    wx.navigateTo({
      url: '/pages/city/city',
    })
  },
  // 手机
  setlianxiren: function(e) {
    this.setData({
      ['form.contactName']: e.detail.value
    })
  },

  setlianxirenphone: function(e) {
    var reg = /^1[3-9]\d{9}$/
    let value = e.detail.value.replace(/\D/g, '')
    // console.log(value);
    // if (reg.test(value)) {
    //   // Toast('贷款金额上限不可超过1000000万元！');
    // } else {
    //   Toast("手机号格式不正确")
    // }
    this.setData({
      ['form.contactPhone']: value
    })
  },
  loanmoneyblur: function() {
    if (this.data.form.loanAmount > 100000) {
      Toast('贷款金额上限不可超过10亿元！');
      this.setData({
        ['form.loanAmount']: 100000
      })
    } else {
      this.setData({
        ['form.loanAmount']: this.validateNumber(this.data.form.loanAmount)
      })
    }
  },
  setloanmoney: function(e) {
    if (this.data.form.loanAmount > 10000) {
      Toast('贷款金额上限不可超过10000万元！');
      this.setData({
        ['form.loanAmount']: 10000
      })
    } else {
      this.setData({
        ['form.loanAmount']: this.validateNumber(e.detail.value)
      })
    }
  },
  switchChange: function(e) {
    console.log(e);
    this.setData({
      ['form.isoneloan']: e.detail
    })
  },
  ispledgeChange: function(e) {
    console.log(e);
    this.setData({
      ['form.ispledge']: e.detail
    })
    if (e.detail == false) {
      this.setData({
        ['form.pledgegood']: ''
      })
    }
  },
  // 抵押物
  setpledgegood: function (e) {
    this.setData({
      ['form.pledgegood']: e.detail.value
    })
  },
  // 选择银行
  onChangeselebank: function(e) {
    this.setData({
      selectbanklist: event.detail,
    });
  },
  toggle: function(e) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    //console.log(checkbox);
    checkbox.toggle();
  },
  seletbanklistIshow: function() {
    wx.navigateTo({
      url: '/pages/bankList/bankList',
    })
  },
  closebankClick: function(e) {
    //console.log(e.currentTarget.dataset.tagindex);
    let arr = this.data.banklist;
    arr.splice(e.currentTarget.dataset.tagindex, 1)
    //console.log(arr);
    this.setData({
      banklist: arr
    })
    getApp().globalData.banklist = this.data.banklist;
  },
  validateNumber: function(e) {
    return val.replace(/\D/g, '')
  },
  clickoverlay: function() {
    //console.log(222);
    this.setData({
      proselectisshow: false
    })
  },
  // 提交申请
  submitApply: function() {
    var reg = /^1[3-9]\d{9}$/
    var arr = []
    console.log(this.data.banklists);
    if (this.data.banklists.length > 0) {
      this.data.banklist.forEach((item, index) => {
        this.data.banklists.forEach((jitm, jindex) => {
          if (item == jitm.bankName) {
            let obj = {
              id: jitm.id,
              bankName: jitm.bankName
            }
            arr.push(obj)
          }
        })
      })
    }

    if (this.data.form.contactName !== '' && this.data.form.contactPhone !== '' && this.data.form.loanAmount !== '' && this.data.form.enterpriseName !== '' && this.data.form.enterpriseCode !== '') {
      console.log(arr);
      if (reg.test(this.data.form.contactPhone)) {
        if (this.data.form.ispledge && this.data.form.pledgegood == "") {
          Toast("请先输入您要抵押的物品！")
        } else {
          let pardata = {
            contactName: this.data.form.contactName,
            contactPhone: this.data.form.contactPhone,
            enterpriseName: this.data.form.enterpriseName,
            enterpriseCode: this.data.form.enterpriseCode,
            bankList: arr,
            loanAmount: this.data.form.loanAmount,
            isFirst: this.data.form.isoneloan ? 1 : 0,
            city: this.data.cityName,
            // 添加抵押物字段
            isMortgage: this.data.form.ispledge ? 1 : 0,
            pledge: this.data.form.pledgegood
          }

          console.log(pardata);
          getApp().globalData.request("/financing/submitApply", pardata, "POST").then(res => {
            console.log(res);
            if (res.code == 1) {
              // this.setData({
              //   applysuccessdialog: true
              // })
              Toast("您的需求已提交成功，可在申请记录中查看进度。")
              // 清除表单
              this.clearForm()
              wx.switchTab({
                url: '/pages/historypro/historypro',
              })
            } else {
              Toast(res.message);
            }
          })
        }
      } else {
        Toast("您输入的手机号不正确,请重新输入！")
      }
    } else {
      Toast('请先完善信息！');
    }
  },
  // 前往个人中心
  toindexClcik() {
    wx.switchTab({
      url: '/pages/Home/Home',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(getApp().globalData);
    // 获取手机号
    // this.initInfos()
    // 拿到选择的企业 和 银行列表
    // 获取当前城市
    this.setData({
      ['fabuData.cityName']: getApp().globalData.cityName,
      ['fabuData.banklist']: getApp().globalData.banklist,
      ['fabuData.form.contactPhone']: wx.getStorageSync('userInfo').phone,
    })
    // this.getBanklist()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})